package com.smart.seckilldemo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.smart.seckilldemo.commons.exception.ServiceException;
import com.smart.seckilldemo.commons.exception.StatusCode;
import com.smart.seckilldemo.commons.result.ResponseResult;
import com.smart.seckilldemo.commons.result.ResultCodeEnum;
import com.smart.seckilldemo.mapper.UserMapper;
import com.smart.seckilldemo.pojo.User;
import com.smart.seckilldemo.service.UserService;
import com.smart.seckilldemo.utils.CookieUtils;
import com.smart.seckilldemo.utils.MD5Utils;
import com.smart.seckilldemo.utils.UUIDUtils;
import com.smart.seckilldemo.commons.vo.LoginVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
public class UserServiceImpl implements UserService {

    @Resource
    UserMapper userMapper;

    @Resource
    private RedisTemplate redisTemplate;

    @Resource
    UserService userService;


    @Override
    public ResponseResult login(LoginVo loginVo, HttpServletRequest request, HttpServletResponse response) {
        try {
            String uuid = UUIDUtils.uuid();
            String name=loginVo.getUsername();
            String password=loginVo.getPassword();
            if(name==null||password==null){
                return ResponseResult.error();
            }
        QueryWrapper qw=new QueryWrapper();
        qw.eq(User.COL_NAME, name);
        User user = userMapper.selectOne(qw);
        if(user.getId()==null){
            //账号为空
            return ResponseResult.error(ResultCodeEnum.ACCOUNT_LOGIN_ERROR);
        }
        //判断密码
        String dbPassword = MD5Utils.inputPassToDBPassword(password);
            if (dbPassword.equals(user.getPassword())){
                 //密码正确
                 //生成cookie
                    request.getSession().setAttribute("userTicket",uuid);
                    CookieUtils.setCookie(request,response,"userTicket",uuid);
//                    redis 的方式
                    //将用户信息存入redis
                    redisTemplate.opsForValue().set("user:"+uuid,user,500, TimeUnit.SECONDS);

                    return ResponseResult.success(ResultCodeEnum.SUCCESS);
                }else{
                    //密码错误
                    return ResponseResult.error(ResultCodeEnum.ACCOUNT_LOGIN_ERROR);
                }
        }catch (Exception e){
            throw new ServiceException(StatusCode.LOGIN_ERROR);
        }
    }

    /**
     * 根据 cookie 的key 去从 redis 中获取用户
     * @param userTicket
     * @return
     */
    @Override
    public User getUserByCookie(String userTicket, HttpServletRequest request, HttpServletResponse response) {
        //为空不查找
        if(StringUtils.isEmpty(userTicket)){
            return null;
        }
        User user = (User) redisTemplate.opsForValue().get("user:" + userTicket);
        //有值 无cookie 添加cookie
        if(user!=null){
            CookieUtils.setCookie(request,response,"userTicket",userTicket);
            return user;
        }else {
            throw new ServiceException(StatusCode.LOGIN_DATE_ERROR);
        }

    }

    /**
     * 注册用户
     * @param loginVo
     * @return
     */
    @Override
    public ResponseResult registerUser(LoginVo loginVo) {
       if(loginVo.getUsername()==null){
            return ResponseResult.success(ResultCodeEnum.PARAMS_NOT_IS_BLANK);
        }
        String username = loginVo.getUsername();
        User userByName = userService.getUserByName(username);
        if(userByName.getName()!=null){
            //用户存在
            return ResponseResult.success(ResultCodeEnum.ACCOUNT_IS_EXISTENT);
        }
        String password = loginVo.getPassword();
        User user = new User();
        user.setName(username);
        //密码加密
        String dbPassword = MD5Utils.inputPassToDBPassword(password);
        user.setPassword(dbPassword);
        int insert = userMapper.insert(user);
        if(insert!=0){
            return ResponseResult.success(ResultCodeEnum.SUCCESS);
        }else {
            return ResponseResult.error(ResultCodeEnum.ACCOUNT_IS_EXISTENT);
        }
    }


    /**
     * 通过名称查询用户
     * @param name
     * @return
     */
    @Override
    public User getUserByName(String name) {
        QueryWrapper<User> qw = new QueryWrapper<>();
        qw.eq(User.COL_NAME,name);
        return userMapper.selectOne(qw);
    }

    @Override
    public User getUserById(Long userId) {
        QueryWrapper<User> wq = new QueryWrapper<>();
        wq.eq(User.COL_ID,userId);
        return userMapper.selectOne(wq);
    }

    /**
     * 更新密码
     * @param userTicket
     * @param password
     * @return
     */
    @Override
    public ResponseResult updatePassword(String userTicket,String password,HttpServletRequest request, HttpServletResponse response) {

        User user = getUserByCookie(userTicket, request, response);
        if(user==null){
            throw new ServiceException(StatusCode.KEY_ERROR);
        }
        user.setPassword(MD5Utils.inputPassToDBPassword(password));
        int i = userMapper.updateById(user);
        if(i==i){
            //成功
            redisTemplate.delete("user:"+userTicket);
            return ResponseResult.success();
        }
        //失败
        return ResponseResult.error(ResultCodeEnum.ACCOUNT_IS_UPDATE_PASSWORD_ERROR);
    }


}